package com.qk.management.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qk.common.PageResult;
import com.qk.common.enums.ParamEnum;
import com.qk.common.exception.CommonException;
import com.qk.common.util.JwtUtils;
import com.qk.domain.user.UserDO;
import com.qk.dto.user.UserDTO;
import com.qk.dto.user.UserLoginDTO;
import com.qk.entity.Role;
import com.qk.entity.User;
import com.qk.management.mapper.RoleMapper;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.UserService;
import com.qk.vo.user.UserLoginVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;

    private static final String DEFAULT_PASSWORD_SUFIX = "123";

    private static final Integer USER_STATUS_NORMAL = 0;

    @Override
    public PageResult<UserDO> getUsers(UserDTO userDto) {

        PageHelper.startPage(userDto.getPage(), userDto.getPageSize());

        // 执行查询
        List<UserDO> result = userMapper.getUsers(userDto);

        // 获取分页信息
        Page<UserDO> pageInfo = (Page<UserDO>) result;

        /*使用@Builder注解创建对象并封装成PageResult对象*/
        return PageResult.<UserDO>builder()
                .total(Long.valueOf(pageInfo.getTotal()).intValue())
                .rows(pageInfo.getResult())
                .build();
    }

    @Override
    public void addUser(User user) {
        // 参数校验： 工具类处理 hutool 工具类
        boolean hasNull = BeanUtil.hasNullField(user, "id", "password", "roleId", "deptId", "image", "remark", "updateTime", "createTime");
        if (hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        // 补全数据
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateTime(LocalDateTime.now());
        // 设置默认密码
        // 原始密码（明文密码）
        String rawPassword = new StringBuilder(user.getUsername()).append(DEFAULT_PASSWORD_SUFIX).toString();
        // MD5算法对原始密码进行消息摘要处理得到字符串（密文密码）
        String encodedPassword = DigestUtils.md5DigestAsHex(rawPassword.getBytes());
        user.setPassword(encodedPassword);
        // 插入
        userMapper.insert(user);
    }

    @Override
    public void deleteUser(List<Integer> ids) {
        userMapper.deleteByIds(ids);
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.selectById(id);
    }

    @Override
    public void updateUser(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.updateById(user);
    }

    @Override
    public UserLoginVO login(UserLoginDTO dto) {
        boolean hasNull = BeanUtil.hasNullField(dto);
        if (hasNull) {
            CommonException.throwCommonException(ParamEnum.PARAM_ERROR);
        }
        User dbUser = userMapper.getUserByUsername(dto.getUsername());
        if (Objects.isNull(dbUser)) {
            CommonException.throwCommonException(ParamEnum.LOGIN_USERNAME_ERROR);
        }
        String encodedPassword = DigestUtils.md5DigestAsHex(dto.getPassword().getBytes());
        if (!Objects.equals(dbUser.getPassword(), encodedPassword)) {
            CommonException.throwCommonException(ParamEnum.LOGIN_PASSWORD_ERROR);
        }
        if(Objects.equals(dbUser.getStatus(), USER_STATUS_NORMAL)){
            CommonException.throwCommonException(ParamEnum.LOGIN_USERSTATUS_ERROR);
        }
        Role role = roleMapper.getRoleById(dbUser.getRoleId());
        Map<String, Object> claims = new HashMap<>();
        claims.put("id" , dbUser.getId());
        claims.put("username" , dbUser.getUsername());
        return UserLoginVO.builder()
                .id(dbUser.getId())
                .username(dbUser.getUsername())
                .name(dbUser.getName())
                .image(dbUser.getImage())
                .roleLabel(role.getLabel())
                .token(JwtUtils.generateToken(claims))
                .build();
    }

    @Override
    public List<User> list() {
        return userMapper.list();
    }

    @Override
    public List<User> listByRole(String roleLabel) {
        // 根据角色label 查询角色表获取角色
        Role role = roleMapper.selectByLabel(roleLabel);
        return userMapper.listByRole(role.getId());
    }
}
